import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'

interface VoiceHistoryItem {
  id: number;
  text: string;
  confidence: number;
  timestamp: string;
  language: string;
}

interface VoiceSettings {
  autoSend: boolean;
  continuous: boolean;
  interimResults: boolean;
  maxAlternatives: number;
  noiseReduction: boolean;
  echoCancellation: boolean;
  autoGainControl: boolean;
}

interface VoiceStoreState {
  // 录音状态
  isRecording: boolean;
  isProcessing: boolean;
  recordingDuration: number;
  recordingStartTime: number | null;

  // 语音识别
  recognitionText: string;
  finalText: string;
  confidence: number;
  language: string;

  // 音频数据
  audioBlob: Blob | null;
  audioUrl: string | null;
  waveformData: number[];

  // 错误处理
  error: string | null;
  lastError: string | null;

  // 历史记录
  voiceHistory: VoiceHistoryItem[];
  maxHistoryItems: number;

  // 设置
  settings: VoiceSettings;

  // 方法
  startRecording: () => void;
  stopRecording: () => void;
  updateRecordingDuration: () => void;
  setAudioData: (blob: Blob, url: string) => void;
  updateWaveform: (data: number[]) => void;
  setRecognitionText: (text: string, isFinal?: boolean, confidence?: number) => void;
  addToHistory: (text: string, confidence: number) => void;
  clearHistory: () => void;
  removeHistoryItem: (id: number) => void;
  setLanguage: (language: string) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
  reset: () => void;
  updateSettings: (newSettings: Partial<VoiceSettings>) => void;
  getRecordingStatus: () => 'error' | 'recording' | 'processing' | 'idle';
  getFormattedDuration: () => string;
  getCurrentText: () => string;
  hasAudioData: () => boolean;
  getStats: () => any;
}

export const useVoiceStore = create<VoiceStoreState>()(
  subscribeWithSelector((set, get) => ({
    // 录音状态
    isRecording: false,
    isProcessing: false,
    recordingDuration: 0,
    recordingStartTime: null,

    // 语音识别
    recognitionText: '',
    finalText: '',
    confidence: 0,
    language: 'zh-CN',

    // 音频数据
    audioBlob: null,
    audioUrl: null,
    waveformData: [],

    // 错误处理
    error: null,
    lastError: null,

    // 历史记录
    voiceHistory: [],
    maxHistoryItems: 50,

    // 设置
    settings: {
      autoSend: true,
      continuous: false,
      interimResults: true,
      maxAlternatives: 1,
      noiseReduction: true,
      echoCancellation: true,
      autoGainControl: true
    },

    // 开始录音
    startRecording: () => {
      set({
        isRecording: true,
        isProcessing: false,
        recordingStartTime: Date.now(),
        recordingDuration: 0,
        recognitionText: '',
        finalText: '',
        error: null,
        audioBlob: null,
        audioUrl: null,
        waveformData: []
      })
    },

    // 停止录音
    stopRecording: () => {
      const { recordingStartTime } = get()
      const duration = recordingStartTime ? Date.now() - recordingStartTime : 0
      
      set({
        isRecording: false,
        isProcessing: true,
        recordingDuration: duration
      })
    },

    // 更新录音时长
    updateRecordingDuration: () => {
      const { recordingStartTime, isRecording } = get()
      if (isRecording && recordingStartTime) {
        const duration = Date.now() - recordingStartTime
        set({ recordingDuration: duration })
      }
    },

    // 设置音频数据
    setAudioData: (blob: Blob, url: string) => {
      set({
        audioBlob: blob,
        audioUrl: url,
        isProcessing: false
      })
    },

    // 更新波形数据
    updateWaveform: (data: number[]) => {
      set({ waveformData: data })
    },

    // 设置识别文本
    setRecognitionText: (text: string, isFinal: boolean = false, confidence: number = 0) => {
      console.log('🎤 VoiceStore: 设置识别文本:', { text, isFinal, confidence })
      
      if (isFinal) {
        console.log('✅ VoiceStore: 设置最终文本:', text)
        set({
          finalText: text,
          recognitionText: '',
          confidence,
          isProcessing: false
        })
        
        // 添加到历史记录
        get().addToHistory(text, confidence)
      } else {
        console.log('🔄 VoiceStore: 设置临时文本:', text)
        set({
          recognitionText: text,
          confidence
        })
      }
      
      // 打印当前状态
      const state = get()
      console.log('📊 VoiceStore: 当前状态:', {
        finalText: state.finalText,
        recognitionText: state.recognitionText,
        confidence: state.confidence,
        isProcessing: state.isProcessing
      })
    },

    // 添加到历史记录
    addToHistory: (text: string, confidence: number) => {
      const { voiceHistory, maxHistoryItems } = get()

      const historyItem: VoiceHistoryItem = {
        id: Date.now(),
        text,
        confidence,
        timestamp: new Date().toISOString(),
        language: get().language
      }

      const newHistory = [historyItem, ...voiceHistory].slice(0, maxHistoryItems)
      set({ voiceHistory: newHistory })
    },

    // 清除历史记录
    clearHistory: () => {
      set({ voiceHistory: [] })
    },

    // 删除历史记录项
    removeHistoryItem: (id: number) => {
      const { voiceHistory } = get()
      set({
        voiceHistory: voiceHistory.filter(item => item.id !== id)
      })
    },

    // 设置语言
    setLanguage: (language: string) => {
      set({ language })
    },

    // 设置错误
    setError: (error: string | null) => {
      set({
        error,
        lastError: error,
        isRecording: false,
        isProcessing: false
      })
    },

    // 清除错误
    clearError: () => {
      set({ error: null })
    },

    // 重置状态
    reset: () => {
      set({
        isRecording: false,
        isProcessing: false,
        recordingDuration: 0,
        recordingStartTime: null,
        recognitionText: '',
        finalText: '',
        confidence: 0,
        audioBlob: null,
        audioUrl: null,
        waveformData: [],
        error: null
      })
    },

    // 更新设置
    updateSettings: (newSettings: Partial<VoiceSettings>) => {
      set({
        settings: { ...get().settings, ...newSettings }
      })
    },

    // 获取录音状态
    getRecordingStatus: () => {
      const { isRecording, isProcessing, error } = get()
      
      if (error) return 'error'
      if (isRecording) return 'recording'
      if (isProcessing) return 'processing'
      return 'idle'
    },

    // 格式化录音时长
    getFormattedDuration: () => {
      const { recordingDuration } = get()
      const seconds = Math.floor(recordingDuration / 1000)
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      
      if (minutes > 0) {
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
      return `${remainingSeconds}s`
    },

    // 获取当前文本
    getCurrentText: () => {
      const { finalText, recognitionText } = get()
      const currentText = finalText || recognitionText
      console.log('📝 VoiceStore: 获取当前文本:', { finalText, recognitionText, currentText })
      return currentText
    },

    // 检查是否有音频数据
    hasAudioData: () => {
      const { audioBlob } = get()
      return !!audioBlob
    },

    // 获取统计信息
    getStats: () => {
      const { voiceHistory, settings, language } = get()
      
      return {
        totalRecordings: voiceHistory.length,
        averageConfidence: voiceHistory.length > 0 
          ? voiceHistory.reduce((sum, item) => sum + item.confidence, 0) / voiceHistory.length 
          : 0,
        currentLanguage: language,
        settings
      }
    }
  }))
)

// 自动更新录音时长
setInterval(() => {
  const { updateRecordingDuration, isRecording } = useVoiceStore.getState()
  if (isRecording) {
    updateRecordingDuration()
  }
}, 100) // 每100ms更新一次
